import { useState, useEffect } from 'react'
import HeaderNav from "@/components/header-nav"
import styles from "./index.module.less"
import classnames from 'classnames'
import FooterNav from "@/components/footer-nav"
import { NavBar, Avatar, List, Input, Button, Space, Checkbox } from 'antd-mobile';
import { LeftOutlined, UserOutlined, MessageOutlined } from '@ant-design/icons';
// import { Generate } from "../../lib/script"
const { getUserWorldBookDetails, getWorldBookRoleChatList, createChat, editChat } = $globalServicer('world')
const { getChatDetail } = $globalServicer('chat')

import { useSearchParams } from 'react-router-dom'
const Detail = () => {
  const customNavigate = $globalNavigate()
  const [count, setCount] = useState(0)
  const [textValue, setTextValue] = useState('')
  const [num, setNum] = useState(0)
  const [params] = useSearchParams();
  console.log("🚀 ~ ItemCrad ~ params:", params)
  const type = params.get('type');
  const sendId = params.get('sendId');
  const groupType = params.get('groupType');
  const chatGroupId = params.get('chatGroupId');
  const name = params.get('name');

  const userWorldId = params.get('userWorldId')
  const [groupUserList, setGroupUserList] = useState([])
  const [worldInfo, setWorldInfo] = useState(null)
  const navigate = useNavigate()
  const getData = () => {
    const n = (new Date()).getTime()
    setNum(n)
  }

  const sendMessage = async (id) => {
    window.selectCharacterById(id);
    const Elements = document.getElementsByClassName('no-blur')
    console.log("🚀 ~ sendMessage ~ Elements:", Elements)
    Elements[1].style.display = 'block';
    console.log(`-----发送事件`);
    await window.eventSource.emit('chat_id_changed', 'AA - 2024-9-1 @03h 34m 57s 372ms');
    const textArea = document.getElementById('send_textarea');
    console.log("🚀 ~ sendMessage ~ document:", document)
    console.log("🚀 ~ sendMessage ~ textArea:", textArea)
    // textArea.value = '22222';
    // const send_but = document.getElementById('send_but');
    // send_but.click();
  }
  const backWorldBookDetail = () => {
    const Elements = document.getElementsByClassName('no-blur')
    console.log("🚀 ~ sendMessage ~ Elements:", Elements)
    customNavigate(-1)
    // if (Elements.length) {
    //   if (Elements[1].style.display === 'none') {
    //     customNavigate(-1)
    //   } else {
    //     Elements[1].style.display = 'none';
    //   }
    // } else {
    //   customNavigate(-1)
    // }
  }
  const createNewGroupChat = () => {
    let data = {
      type: 2,
      roles: groupUserList.filter(item => item.checked).map(item => item.id)
    }
    console.log('====>', data);
    if (groupType === 'edit' && chatGroupId) {
      data.id = chatGroupId
      delete data.type
      editChat(data).then(res => {
        console.log('修改群聊res', res)
        customNavigate('/chatlist')
      })
    } else {
      createChat(data).then(res => {
        console.log('创建群聊res', res)
        customNavigate('/chatlist')
      })
    }

  }
  const handleTagCheck = (current) => {
    console.log(current);
    const newGroupUserList = groupUserList.map(item => {
      if (item.id === current.id) {
        return {
          ...item,
          checked: !item.checked
        }
      }
      return item
    })
    setGroupUserList(newGroupUserList)
  }
  useEffect(() => {
    const Elements = document.getElementsByClassName('no-blur')
    console.log("🚀 ~ sendMessage ~ Elements:", Elements)
    if (Elements.length) {
      Elements[1].style.display = 'none';
    }
    if (userWorldId) {
      getUserWorldBookDetails(userWorldId).then(res => {
        setWorldInfo(res)
        if (sendId) {
          getChatDetail(sendId).then(chatRes => {
            const result = res.roles.map(item => {
              const isChecked = chatRes.roles.some(role => role.id === item.id)
              return {
                ...item,
                checked: isChecked
              }
            })
            setGroupUserList(result)
            return
          })
        } else {
          setGroupUserList(res.roles.map(item => ({
            ...item,
            checked: false
          })))
        }
      });
    }
  }, [])
  return (
    <div className="warp">
      <div className="header">
        {/* <HeaderNav title="详情" ></HeaderNav> */}
        <HeaderNav
          backArrow={true}
          onBack={backWorldBookDetail}
          title={type === '1' ? '发起群聊' : '融合世界角色'}
        // styleObj={{ color: '#fff' }}
        >
        </HeaderNav>
      </div>
      <div className={styles.content_body_warp}>
        <div className={styles.content_body}>
          <div className={styles.content_body_top}>
            <p>{worldInfo?.world_name}</p>
            <div className={styles.content_body_top_section}>
              {
                groupUserList?.filter(item => item.checked)?.map(item => (<div className={styles.content_body_top_section_select}>
                  <img src={item?.cover} alt="" />
                </div>))
              }
            </div>
          </div>
          <List style={{ flex: 1, overflowY: 'auto' }}>
            {type === '1' && groupUserList?.map(item => (
              <List.Item
                key={item.id}
              >
                <div className={styles.roleItem}>
                  <div className={styles.itemTop}>
                    <div className={styles.itemLeft}>
                      <img src={item.cover} alt="" />
                      <span className={styles.itemName}>{item.name}</span>
                    </div>
                    {
                      type === '1' && (
                        <div className={styles.itemRight}>
                          <Checkbox checked={item.checked} onChange={() => handleTagCheck(item)} />
                        </div>)
                    }
                  </div>
                </div>
              </List.Item>
            ))}
          </List>
        </div>
      </div>
      {
        type === '1' && (
          <div className={styles.button_wrap} >
            <Button color='primary' shape='rounded' disabled={groupUserList?.filter(item => item.checked)?.length < 2} onClick={createNewGroupChat}>发起群聊</Button>
          </div>
        )
      }
    </div>
  );
};

export default Detail;
